package com.liankuan.console.util;

import com.liankuan.console.common.ResultEnum;
import com.liankuan.console.dto.Strategy;
import com.liankuan.console.exception.ServiceException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.util.ArrayList;
import java.util.List;

/**
 * @author bobo
 * 用来执行策略jar包的启动
 */
@Component
@Slf4j
public class StrategyShell {

    private Config config;

    @Autowired
    public StrategyShell(Config config) {
        this.config = config;
    }


    /**
     * 第一次创建策略时启动的脚本
     *
     * @param strategy
     * @return
     */
    public void CreateStrategyShell(Strategy strategy) {
        String shellPath = config.getJarCopyShellFile();
        //准备要执行的脚本--+脚本所需要的参数
        String strategyName = strategy.getJarName().substring(0, strategy.getJarName().length() - 4) + "-" + strategy
                .getId();

        String[] cmd = {"/bin/sh", "-c", shellPath + " " + strategyName + " " + strategy
                .getJarName()};

        runShell(cmd);
    }


    /**
     * 更新策略状态的脚本--- 也包含删除策略的操作
     *
     * @param jarState
     * @param strategy
     * @return
     */
    public void UpdateStrategySateShell(String jarState, Strategy strategy) {
        String shellPath = config.getJarStartShellFile();
        //准备要执行的脚本--+脚本所需要的参数
        String strategyName = strategy.getJarName().substring(0, strategy.getJarName().length() - 4) + "-" + strategy
                .getId();


        String[] cmd = {"/bin/sh", "-c", shellPath + " " + jarState + " " + strategy.getJarName() + " " +
                strategyName + " " + strategy.getParams() + " " + strategy.getEmail() + " " + strategy.getId()};

        runShell(cmd);
    }

    /**
     * 注:如果sh中含有awk,一定要按new String[]{"/bin/sh","-c",shStr}写,才可以获得流.
     *
     * @param params
     * @return
     */
    private List<String> runShell(String[] params) {
        List<String> strList = new ArrayList<String>();
        try {
            Process process;
            process = Runtime.getRuntime().exec(params);
            InputStreamReader ir = new InputStreamReader(process
                    .getInputStream());
            LineNumberReader input = new LineNumberReader(ir);
            String line;

            //执行脚本时防止该线程提前结束所以等待
            process.waitFor();
            while ((line = input.readLine()) != null) {
                strList.add(line);
            }
            return strList;
        } catch (Exception e) {
            throw new ServiceException(ResultEnum.SHELL_FAILED);
        }

    }
}
